//
//  QSViewList.m
//  Gunz
//
//  Created by Joggy on 16/8/22.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "QSViewList.h"

@interface QSViewList ()<UIScrollViewDelegate> {
    
    UIScrollView *scroll;
    CGFloat scrollContentBottom;
    
}

@end

@implementation QSViewList

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height + 1);
    scroll.delegate = self;
    scrollContentBottom = 0;
    [self addSubview:scroll];
    
    _data = [[NSMutableArray alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNewQSViewByNotification:) name:QSViewCellDataNotification object:nil];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEdit)];
    [self addGestureRecognizer:tapGesture];
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame qsData:(NSArray *)array {
    self = [self initWithFrame:frame];
    
    for(NSDictionary *dic in array) {
        [self addQSView:[[QSViewCell alloc] initWithAttributes:dic]];
    }
    
    return self;
}

- (instancetype)initWithQSData:(NSArray *)array {
    self = [self initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight) qsData:array];
    return self;
}

- (void)addQSView:(QSViewCell*)qsView {
    CGPoint point = CGPointMake(self.frame.size.width/2, scrollContentBottom + qsView.frame.size.height/2);
    qsView.center = point;
    [scroll addSubview:qsView];
    [_data addObject:qsView.question];
    scrollContentBottom = qsView.frame.origin.y + qsView.frame.size.height;
    if(scrollContentBottom + 64 > scroll.frame.size.height) {
        scroll.contentSize = CGSizeMake(scroll.frame.size.width, scrollContentBottom + 64);
    }
    else {
        scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height + 1);
    }
    [scroll scrollRectToVisible:CGRectMake(0, scroll.contentSize.height - scroll.frame.size.height, scroll.frame.size.width, scroll.frame.size.height) animated:true];
}

- (void)addNewQSViewByNotification:(NSNotification*)notification {
    QSViewCell *cell = [[QSViewCell alloc] initWithAttributes:notification.userInfo];
    [self addQSView:cell];
}

- (void)endEdit {
    [self endEditing:true];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self endEdit];
    NSLog(@"endEdit");
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
